﻿using StackExchange.Profiling;
using StackExchange.Profiling.Data;
using System;
using System.Data;
using System.Data.SqlClient;
namespace SXFramWork.Core
{
    public  class DbContext: IDbContext
    {
        //数据库连接字符串
        private string ConnStr { get; }

        //当前进行的工作单元
        public IUnitOfWork CurrentUow { get; set; }
        public DbContext(string dbConnStr="")
        {
            var dbType = ConfigHelper.app(new string[] { "DBConnection", "Type" }).To_Int();
            if (dbType == 0)//sqlserver
            {
               this.ConnStr = dbConnStr == "" ? ConfigHelper.app(new string[] { "DBConnection", "SqlServer" }) :dbConnStr;
            }
            else//mysql
            {
                this.ConnStr = dbConnStr == "" ? ConfigHelper.app(new string[] { "DBConnection", "MySql" }) : dbConnStr;
            }
         
            if (this.ConnStr.IsNull()) throw new Exception("初始化DbContext失败，数据库连接字符串不能为空！");
        }
        /// <summary>
        /// 创建新的工作单元 
        /// </summary>
        /// <returns></returns>
        public IUnitOfWork NewUnitOfWork()
        {
            var con = NewConnection();
            con.Open();
            CurrentUow= new UnitOfWork(con.BeginTransaction(IsolationLevel.ReadUncommitted));
            return CurrentUow;
        }
        /// <summary>
        /// 创建新的工作单元
        /// </summary>
        /// <returns></returns>
        public IUnitOfWork NewUnitOfWork(IsolationLevel isolationLevel)
        {
            var con = NewConnection();
            con.Open();
            CurrentUow= new UnitOfWork(con.BeginTransaction(isolationLevel));
            return CurrentUow;
        }
        /// <summary>
        /// 创建新的连接
        /// </summary>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public IDbConnection NewConnection(IDbTransaction transaction = null)
        {
            if (transaction != null)
                return transaction.Connection;
            var dbtype = ConfigHelper.app("DBConnection", "Type").To_Int();
            var conn = new ProfiledDbConnection(new SqlConnection(ConnStr), MiniProfiler.Current);
            return conn;
        }
        /// <summary>
        /// 获取当前上下文数据库连接字符串
        /// </summary>
        /// <returns></returns>
        public string GetConnectionStr()
        {
            return ConnStr;
        }

        /// <summary>
        /// 获取当前上下文数据库连接字符串
        /// </summary>
        /// <returns></returns>
        public IUnitOfWork GetCurrentUow()
        {
            return CurrentUow;
        }
    }
}
